<template>
<!-- 慢性病分类管理 -->
  <div class="chronic-disease-category-container">
    <!-- 搜索栏 -->
    <div class="search-container">
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="疾病名称">
              <el-input
                v-model="searchForm.diseaseName"
                placeholder="请输入疾病名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="6" class="search-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增慢性病分类
      </el-button>
    </div>

    <!-- 表格 -->
    <div>
      <el-table
        :data="tableData"
        border
        style="width: 100%; display: flex"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="diseaseId" label="疾病ID" width="100" align="center" />
        <el-table-column prop="diseaseCode" label="疾病编码" width="120" align="center" />
        <el-table-column prop="pinyinCode" label="拼音码" width="120" align="center" />
        <el-table-column prop="diseaseName" label="疾病名称" width="120" align="center" />
        <el-table-column prop="description" label="疾病类别" width="200" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.updateTime, 'YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="mini" type="primary" plain @click="handleEdit(row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      @close="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病编码" prop="diseaseCode">
              <el-input v-model="formData.diseaseCode" placeholder="请输入疾病编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼音码" prop="pinyinCode">
              <el-input v-model="formData.pinyinCode" placeholder="请输入拼音码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="疾病名称" prop="diseaseName">
              <el-input v-model="formData.diseaseName" placeholder="请输入疾病名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="疾病类别" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入疾病类别"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="formData.createTime"
                type="datetime"
                placeholder="创建时间"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker
                v-model="formData.updateTime"
                type="datetime"
                placeholder="更新时间"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
import { formatDate } from '@/utils/date';

export default {
  name: 'ChronicDiseaseCategory',
  data() {
    return {
      searchForm: {
        diseaseName: '',
        diseaseCode: '',
        pinyinCode: ''
      },
      tableData: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增慢性病分类',
      formData: {
        diseaseId: null,
        diseaseCode: '',
        pinyinCode: '',
        diseaseName: '',
        description: '',
        status: 1,
        createTime: new Date(),
        updateTime: new Date()
      },
      formRules: {
        diseaseCode: [
          { required: true, message: '请输入疾病编码', trigger: 'blur' },
          { min: 1, max: 20, message: '疾病编码长度1-20位', trigger: 'blur' }
        ],
        pinyinCode: [
          { required: true, message: '请输入拼音码', trigger: 'blur' },
          { min: 1, max: 20, message: '拼音码长度1-20位', trigger: 'blur' }
        ],
        diseaseName: [
          { required: true, message: '请输入疾病名称', trigger: 'blur' },
          { min: 2, max: 50, message: '疾病名称长度2-50位', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    formatDate,
    fetchData() {
      this.loading = true;
      request.get('/chronicDiseaseCategory/list', {
        params: {
          current: this.pagination.currentPage,
          size: this.pagination.pageSize,
          diseaseName: this.searchForm.diseaseName,
          diseaseCode: this.searchForm.diseaseCode,
          pinyinCode: this.searchForm.pinyinCode
        }
      })
      .then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records;
          this.pagination.total = res.data.total;
        } else {
          this.$message.error(res.message || '获取数据失败');
        }
      })
      .catch(err => {
        console.error('获取慢性病分类列表失败:', err);
        this.$message.error('加载慢性病分类列表失败');
      })
      .finally(() => {
        this.loading = false;
      });
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchData();
    },
    resetSearch() {
      this.searchForm = {
        diseaseName: '',
        diseaseCode: '',
        pinyinCode: ''
      };
      this.fetchData();
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchData();
    },
    handleAdd() {
      this.dialogTitle = '新增慢性病分类';
      this.resetForm();
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑慢性病分类';
      this.formData = {
        ...row,
        // 确保日期字段是 Date 对象
        createTime: row.createTime ? new Date(row.createTime) : new Date(),
        updateTime: row.updateTime ? new Date(row.updateTime) : new Date()
      };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm(`确认删除疾病 "${row.diseaseName}" 吗？`, '提示', {
        type: 'warning'
      })
      .then(() => {
        request.post(`/chronicDiseaseCategory/delete/${row.diseaseId}`)
        .then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.fetchData();
          } else {
            this.$message.error(res.message || '删除失败');
          }
        })
        .catch(err => {
          console.error('删除失败:', err);
          this.$message.error('删除失败');
        });
      })
      .catch(() => {});
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return;
        
        // 创建一个临时对象，处理日期格式
        const formDataToSubmit = { ...this.formData }
        
        // 将日期对象格式化为 YYYY-MM-DD HH:mm:ss 字符串
        if (formDataToSubmit.createTime instanceof Date) {
          formDataToSubmit.createTime = formatDate(formDataToSubmit.createTime, 'YYYY-MM-DD HH:mm:ss')
        }
        
        // 编辑模式下，自动设置更新时间为当前时间
        if (formDataToSubmit.diseaseId) {
          formDataToSubmit.updateTime = formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
        } else if (formDataToSubmit.updateTime instanceof Date) {
          formDataToSubmit.updateTime = formatDate(formDataToSubmit.updateTime, 'YYYY-MM-DD HH:mm:ss')
        }

        const isEdit = !!this.formData.diseaseId;
        const apiUrl = isEdit ? '/chronicDiseaseCategory/update' : '/chronicDiseaseCategory/create';

        request.post(apiUrl, formDataToSubmit)
        .then(res => {
          if (res.code === 200) {
            this.$message.success(`${this.dialogTitle}成功`);
            this.dialogVisible = false;
            this.fetchData();
          } else {
            this.$message.error(res.message || `${this.dialogTitle}失败`);
          }
        })
        .catch(err => {
          console.error(`${this.dialogTitle}失败:`, err);
          this.$message.error(`${this.dialogTitle}失败`);
        });
      });
    },
    resetForm() {
      this.$refs.formRef && this.$refs.formRef.resetFields();
      this.formData = {
        diseaseId: null,
        diseaseCode: '',
        pinyinCode: '',
        diseaseName: '',
        description: '',
        status: 1,
        createTime: new Date(),
        updateTime: new Date()
      };
    }
  }
};
</script>

<style scoped>
.chronic-disease-category-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;
}

.operation-buttons {
  display: flex;
  margin-bottom: 20px;
}

.operation-buttons > * {
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table {
  font-size: 14px;
}

.el-table th {
  font-weight: bold;
  color: #333;
}

.el-table .cell {
  padding: 8px 0;
}

@media (max-width: 768px) {
  .search-buttons {
    justify-content: flex-start;
    margin-top: 10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
  
  .operation-buttons {
    flex-wrap: wrap;
  }
  
  .operation-buttons > * {
    margin-bottom: 10px;
  }
}
</style>